using System.Collections;
using System.Collections.Generic;
using System.IO;
using cfg;
using cfg.demo;
using cfg.test;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SimpleJSON;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Events;
using YooAsset;
using YooAssetsSystem;

namespace LubanSystem.Samples
{

    /// <summary>
    /// 测试LubanSystem YooAssets插件
    /// </summary>
    public partial class LubanSystemTest_YooAssets : MonoBehaviour
    {
        #region 热更使用 - 非参考代码

        /// <summary>
        /// YooAssets服务
        /// </summary>
        private YAService_Entity yooAssetService;

        /// <summary>
        /// 热更模式
        /// </summary>
        public EPlayMode ePlayMode;

        #endregion

        /// <summary>
        /// LubanSystem服务
        /// </summary>
        private LubanService_Entity lubanService;

        /// <summary>
        /// LubanSystem服务 的 YooAssets服务
        /// </summary>
        private LubanService_Entity_YooAssets lubanService_YooAssets => lubanService.GetComponentOrAdd<LubanService_Entity_YooAssets>();
    }

    public partial class LubanSystemTest_YooAssets
    {
        void Start()
        {
            #region 非参考代码

            if (yooAssetService == null)
                yooAssetService = new YAService_Entity();

            #endregion

            // 初始化LubanSystem服务
            if (lubanService == null)
                lubanService = new LubanService_Entity();
        }

        #region 非参考代码


        #region 下载配置包

        /// <summary>
        /// 下载 分包
        /// </summary>
        public void Test_YooAssetPkgDownload_AddPkg()
        {
            EPlayMode playMode = ePlayMode;
            string url = "https://zongyi-cdn-src.oss-cn-beijing.aliyuncs.com/ddz-app/wx/YooassetTest/TestLuBanSystem";
            string appVersion = "1";
            string packageName = "AddPkg";
            bool isDefaultPackage = false;
            string[] loadTags = new string[0];
            bool isCustomizeUrl = false;

            YAService_Entity.Instance.DownloadPackage(playMode, url, appVersion, packageName, isDefaultPackage, loadTags, isCustomizeUrl,
                    Event_ChangeStateEvent, Event_PatchDoneEvent_AddPkg, Event_UpdateFailedEvent,
                    Event_NeedDownloadEvent)
                .Forget();
        }

        /// <summary>
        /// 回调事件 下载 流程 状态切换
        /// </summary>
        /// <param name="msg"></param>
        private void Event_ChangeStateEvent(string msg)
        {
            Debug.Log($"{GetType().FullName}:: ChangeStateEvent: {msg}");
        }

        /// <summary>
        /// 回调事件 下载 结束 默认包的处理
        /// </summary>
        /// <param name="msg"></param>
        private void Event_PatchDoneEvent_DefaultPackage(string msg)
        {
            Debug.Log($"{GetType().FullName}:: PatchDoneEvent: {msg}");
        }

        /// <summary>
        /// 回调事件 下载 结束 分包的处理
        /// </summary>
        /// <param name="msg"></param>
        private void Event_PatchDoneEvent_AddPkg(string msg)
        {
            Debug.Log($"{GetType().FullName}:: PatchDoneEvent: {msg}");
        }

        /// <summary>
        /// 回调事件 下载 失败
        /// </summary>
        /// <param name="msg"></param>
        private void Event_UpdateFailedEvent(string msg)
        {
            Debug.Log($"{GetType().FullName}:: UpdateFailedEvent: {msg}");
        }

        /// <summary>
        /// 回调事件 下载 需要下载的情况
        /// 里面有个UnityAction，可以给UI来使用
        /// 例如： 给用户提示有多少内容需要下载，点击开始才进行下载
        /// </summary>
        /// <param name="fileNum">总文件数量</param>
        /// <param name="totalSize">总大小</param>
        /// <param name="toDownload">开始下载的事件</param>
        private void Event_NeedDownloadEvent(int fileNum, long totalSize, UnityAction toDownload)
        {
            Debug.Log($"{GetType().FullName}:: Event_NeedDownloadEvent 文件数: {fileNum} -- 总大小: {totalSize}");
            toDownload?.Invoke();
        }

        #endregion

        #endregion

        #region 加载 单个配置文件 - 数据

        /// <summary>
        /// 测试 加载 YooAssets包 单个配置文件 - 数据
        /// </summary>
        public void Test_LoadConfig_YooAssets()
        {
            JArray data = lubanService_YooAssets.LoadConfig_ToJArray_YooAssets("demo_tbreward", "AddPkg");
            Assert.IsNotNull(data);
            data = lubanService_YooAssets.LoadConfig_ToJArray_YooAssets_UniTask("demo_tbreward", "AddPkg").GetAwaiter().GetResult();
            Assert.IsNotNull(data);
            Test_LoconfigTools_ToTable(data);
            Test_LoadSingleTable_Sync();
            Test_LoadSingleTable_Async().Forget();
        }

        /// <summary>
        /// 数据序列化为表
        /// </summary>
        /// <param name="data">数据</param>
        protected void Test_LoconfigTools_ToTable(JArray data)
        {
            cfg.demo.TbReward tbReward = new TbReward(data);
            Assert.IsNotNull(tbReward);
            Debug.Log($"Test_LoconfigTools_ToTable 数据加载完成 tbReward: {JsonConvert.SerializeObject(tbReward)}");
        }

        /// <summary>
        /// 测试 加载单个配置表 - 同步
        /// </summary>
        public void Test_LoadSingleTable_Sync()
        {
            string pkgName = "AddPkg";
            cfg.demo.TbReward tbReward = cfg.Tables.LoadSingle<cfg.demo.TbReward>("demo_tbreward", file =>
            {
                return lubanService_YooAssets.LoadConfig_ToJArray_YooAssets(file, pkgName);
            });
            Assert.IsNotNull(tbReward);
            Debug.Log($"Test_LoadSingleTable_Sync 同步加载完成 tbReward.Get(1001): {JsonConvert.SerializeObject(tbReward.Get(1001))}");
        }

        /// <summary>
        /// 测试 加载单个配置表 - 异步
        /// </summary>
        public async UniTask Test_LoadSingleTable_Async()
        {
            string pkgName = "AddPkg";
            cfg.demo.TbReward tbReward = await cfg.Tables.LoadSingle_Async<cfg.demo.TbReward>("demo_tbreward", async file =>
            {
                return await lubanService_YooAssets.LoadConfig_ToJArray_YooAssets_UniTask(file, pkgName);
            });
            Assert.IsNotNull(tbReward);
            Debug.Log($"Test_LoadSingleTable_Async 异步加载完成 tbReward.Get(1001): {JsonConvert.SerializeObject(tbReward.Get(1001))}");
        }

        #endregion

        #region 加载 单个配置文件 - 常量

        /// <summary>
        /// 测试 加载 YooAssets包 单个配置文件 - 常量
        /// </summary>
        public void Test_LoadConstConfig_YooAssets()
        {
            JArray data = lubanService_YooAssets.LoadConfig_ToJArray_YooAssets("tbconstconfig", "AddPkg");
            Assert.IsNotNull(data);
            Test_LoconfigTools_ToConst(data);
        }

        /// <summary>
        /// 常量序列化为表
        /// </summary>
        /// <param name="data">数据</param>
        protected void Test_LoconfigTools_ToConst(JArray data)
        {
            constconfig config = constconfig.Deserializeconstconfig(data[0]);
            Debug.Log($"Test_LoconfigTools_ToConst 数据加载完成 config: {config.ToString()}");
            Assert.IsFalse(config.DemoBool1);
        }

        #endregion

        #region 加载 所有配置文件

        /// <summary>
        /// 测试 加载 YooAssets包 所有配置文件
        /// </summary>
        public void Test_LoadAllConfig_YooAssets()
        {
            string pkgName = "AddPkg";
            Tables tbs = new cfg.Tables(file =>
            {
                return lubanService_YooAssets.LoadConfig_ToJArray_YooAssets(file, pkgName);
            });
            Assert.IsNotNull(tbs);
            Debug.Log($"Test_LoadAllConfig_YooAssets 数据加载完成 tbs.TbReward.Get(1001): {JsonConvert.SerializeObject(tbs.TbReward.Get(1001))}");

            Test_LoadAllConfig_YooAssets_Async().Forget();
        }

        /// <summary>
        /// 测试 加载 YooAssets包 所有配置文件 - 异步
        /// </summary>
        public async UniTask Test_LoadAllConfig_YooAssets_Async()
        {
            string pkgName = "AddPkg";
            Tables tbs = await cfg.Tables.LoadAsync(async file =>
            {
                return await lubanService_YooAssets.LoadConfig_ToJArray_YooAssets_UniTask(file, pkgName);
            });
            Assert.IsNotNull(tbs);
            Debug.Log($"Test_LoadAllConfig_YooAssets_Async 数据加载完成 tbs.TbReward.Get(1001): {JsonConvert.SerializeObject(tbs.TbReward.Get(1001))}");
        }

        #endregion

    }

}
